<?php

namespace app\api\controller;

use think\Controller;
use think\facade\App;

class Member extends Auth
{
    public function __construct()
    {
        parent::__construct();
        if ($this->role != 1) {
            $this->initreturn('越权操作');
        }
    }

    /**
     * 教练列表
     */
    public function coachList()
    {
        $get = input('get.');

        $where = [];
        if (!empty($get['provinceid'])) {
            $where[] = ['coachprovinceid', '=', $get['provinceid']];
        } else if (!empty($get['longitude']) && !empty($get['latitude'])) {
            $longitude = $get['longitude'];
            $latitude = $get['latitude'];
        } else if (!empty($get['address'])) {
            $result = $this->getgaode($get['address']);
            if ($result['code'] == 1000) {
                if (!empty($result['data'])) {
                    $location = $result['data'];
                    $longitude = empty($location[0]) ? '' : $location[0];
                    $latitude = empty($location[1]) ? '' : $location[1];
                }
            } else {
                return $this->json($result['data'], $result['code'], $result['msg']);
            }
        }

        $where[] = ['isdel', '=', 0];
        $where[] = ['status', '=', 3];
        $data['where'] = $where;
        $tableName = 'coach';

        /*距离排序*/
        if (!empty($longitude) && !empty($latitude)) {
            /*需要传入经纬度，默认正序*/
            $data['field'] = "*, (st_distance(point (longitude,latitude), point (" . htmlspecialchars($longitude) . "," . htmlspecialchars($latitude) . "))*111195/1000 ) as distance";
            $data['order'] = 'distance asc';
        }

        $data['totalCount'] = $this->countTable($tableName, $data);
        $data = $this->buildCount($data);
        $list = $this->listTable($tableName, $data);

        $info = $this->findTable('order', ['where' => [
            ['memberid', '=', $this->userid],
            ['isdel', '=', 0],
            ['status', '=', 2],
        ]]);

        if (!empty($info)) {
            $where = [
                ['coachid', 'in', array_column($list, 'coachid')],
                ['orderid', '=', $info['orderid']],
            ];
            $invitation = $this->listTable('invitation', ['where' => $where, 'field' => 'coachid']);
        }

        foreach ($list as $key => $val) {
            if (!empty($info)) {
                $list[$key]['isinvitation'] = 1;
                foreach ($invitation as $k => $v) {
                    if ($v['coachid'] == $val['coachid']) {
                        $list[$key]['isinvitation'] = 0;
                    }
                }
            } else {
                $list[$key]['isinvitation'] = 0;
            }

            if ($val['coachid'] == $info['issuing']) {
                $list[$key]['isinvitation'] = 0;
            }
        }

        $data['list'] = $list;
        return $this->json($data);
    }

    /**
     * 学员信息编辑
     */
    public function updateMemberInfo()
    {
        $post = input('post.');

        $arr = ['membernickname', 'membertruename', 'memberavatar', 'memberbirthday', 'memberage', 'membersex', 'homeaddress', 'memberqq', 'memberdesc'];
        $data = [];
        foreach ($arr as $key => $val) {
            if (isset($post[$val])) {
                $data[$val] = empty($post[$val]) ? '' : $post[$val];
            }
        }

        if (empty($data)) {
            return $this->json($this->userid, 1000, '编辑成功');
        }

        $where = ['memberid' => $this->userid];
        $update = [
            'where' => $where,
            'data' => $data,
        ];

        $ans = $this->updateTable('member', $update);

        $yx = new \app\common\lib\YxUtils();
        $yx->updateUinfo($this->table . '_' . $this->userid, $data['membertruename']);

        if ($ans) {
            return $this->json($ans, 1000);
        } else {
            return $this->json($ans, 2000);
        }
    }

    public function setInvitation()
    {
        $post = input('post.');
        if (empty($post['coachid'])) {
            return $this->json([], 2000, '参数错误');
        }

        $info = $this->findTable('order', ['where' => [
            ['memberid', '=', $this->userid],
            ['isdel', '=', 0],
            ['status', '=', 1],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '无可邀请订单，请发单后再操作');
        }

        $coach = $this->findTable('coach', [
            'where' => [
                'coachid' => $post['coachid'],
            ],
            'field' => 'coachmobile',
        ]);

        if (empty($coach)) {
            return $this->json([], 2000, '教练账号异常，请邀请其他教练');
        }

        $where = [
            'coachid' => $post['coachid'],
            'orderid' => $info['orderid'],
        ];

        $invitation = $this->findTable('invitation', ['where' => $where]);

        if (empty($invitation)) {
            $data = [
                'memberid' => $this->userid,
                'coachid' => $post['coachid'],
                'orderid' => $info['orderid'],
            ];

            $ans = $this->insertTable('invitation', $data);
            if ($ans) {
                $params = [];
                $params['signName'] = '快通驾驶';
                $params['noticetemplateCode'] = "SMS_189032233";
                $mess = new Mess();
                $mess->sendNoticeByAli($coach['coachmobile'], ['consignee' => $this->user['membertruename'], 'number' => $this->user['membermobile']], $params);

                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $post['coachid'],
                    'reciveutable' => 'coach',
                    'msgtitle' => '您有一条新的邀请',
                    'msgtext' => "您在{$time}有一条邀请订单，学员：{$this->user['membertruename']},联系方式：{$this->user['membermobile']}。"
                ];
                $this->addnotice($notice);
                return $this->json($ans, 1001, '邀请成功');
            } else {
                return $this->json($ans, 2000, '邀请失败');
            }
        } else {
            return $this->json([], 1000, '重复邀请');
        }
    }

    /**
     *  学员发单
     */
    public function addOrder()
    {
        $post = input('post.');
        $builarr = ['trainingcourse' => '培训科目', 'trainingmodel' => '培训车型', 'examinecity' => '考试城市', 'collegename' => '学员姓名', 'collegemobile' => '学员手机', 'collegeage' => '学员年龄', 'collegeaddress' => '地址', 'province' => '省份'];

        $data = [];
        foreach ($builarr as $key => $val) {
            if (empty($post[$key])) {
                return $this->json($post, 2000, '请输入正确' . $val);
            }
            $data[$key] = empty($post[$key]) ? '' : $post[$key];
        }

        if ((int) $data['collegeage'] < 18 || (int) $data['collegeage'] > 70) {
            return $this->json($post, 2000, '驾照最低的年龄要求在18周岁以上，70周岁以下年龄');
        }

        if (empty($post['amount']) || (float) ($post['amount']) <= 0) {
            return $this->json($post, 2000, '请输入正确的单价');
        }

        $data['amount'] = (float)$post['amount'];

        if (empty($post['collegedetailedaddress'])) {
            return $this->json($post, 2000, '请输入详细地址');
        }
        $data['collegedetailedaddress'] = $post['collegedetailedaddress'];

        if ($this->user['membermobile'] != $data['collegemobile']) {
            return $this->json($post, 2000, '学员手机号码与用户不一致');
        }

        $info = $this->findTable('order', ['where' => [
            ['memberid', '=', $this->userid],
            ['isdel', '=', 0],
            ['status', '<', 6],
        ]]);

        if (!empty($info)) {
            return $this->json($post, 2000, '您已存在未完成的订单，当前订单完成才能继续发单');
        }

        if (!empty($post['city'])) {
            $data['city'] = $post['city'];
        }

        if (!empty($post['area'])) {
            $data['area'] = $post['area'];
        }

        if (!empty($post['describe'])) {
            $data['describe'] = $post['describe'];
        }

        $data['memberid'] = $this->userid;

        $ordersn = $this->createOrdersn();
        $data['ordersn'] = $ordersn . $this->userid;

        $address = $data['collegeaddress'] . $data['collegedetailedaddress'];
        $result = $this->getgaode($address);
        if ($result['code'] == 1000) {
            if (!empty($result['data'])) {
                $location = $result['data'];
                $data['longitude'] = empty($location[0]) ? '' : $location[0];
                $data['latitude'] = empty($location[1]) ? '' : $location[1];
            }
        } else {
            return $this->json($result['data'], $result['code'], $result['msg']);
        }

        if (!empty($post['longitude']) && !empty($post['latitude'])) {
            $data['longitude'] = $post['longitude'];
            $data['latitude'] = $post['latitude'];
        }

        $ans = $this->insertTable('order', $data);
        if ($ans) {
            $time = date('Y-m-d H:i:s');
            $notice = [
                'type' => 2,
                'userid' => 0,
                'reciveutype' => 3,
                'reciveuid' => $this->userid,
                'reciveutable' => $this->table,
                'msgtitle' => '发单成功',
                'msgtext' => "您在{$time}发单成功,单号：{$ordersn}, 请赶紧支付吧",
            ];
            $this->addnotice($notice);
            return $this->json($ans, 1001, '发单成功');
        } else {
            return $this->json($ans, 2000, '发单失败');
        }
    }

    /**
     * 订单获取已经抢单的教练
     */
    public function getApplyList()
    {
        $get = input('get.');

        if (empty($get['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }

        $where = $data = [];
        $where = ['coach.status' => 3, 'apply_order.orderid' => $get['orderid']];
        $data['where'] = $where;
        $data['join'] = [
            ['coach coach', 'coach.coachid = apply_order.coachid', 'inner'],
        ];
        $data['field'] = "apply_order.*,coach.coachavatar,coach.coachtruename,coach.coachbirthday,coach.coachid,coach.coachsex";
        $list = $this->listTable('apply_order', $data);
        return $this->json($list, 1000);
    }

    /**
     * 选择已经申请的教练
     */
    public function selectCoach()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }

        if (empty($post['coachid'])) {
            return $this->json([], 2000, '绑定参数错误');
        }

        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 1],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可绑定订单');
        }

        $coach = $this->findTable('coach', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 3],
            ['coachid', '=', $post['coachid']],
        ], 'field' => 'status']);

        if(empty($coach)) {
            return $this->json([], 2000, '教练账号异常，请选择其他教练');
        }

        $where = [
            'coachid' => $post['coachid'],
            'orderid' => $post['orderid'],
        ];
        $apply = $this->findTable('apply_order', ['where' => $where]);
        if (empty($apply)) {
            return $this->json([], 2000, '该教练未申请当前订单');
        }

        if ($info['memberid'] != $this->userid) {
            return $this->json([], 2000, '无权限绑定');
        }

        $where = ['orderid' => $post['orderid']];
        $update = [
            'where' => $where,
            'data' => [
                'coachid' => $post['coachid'],
                'status' => 2,
            ],
        ];

        $log = [
            'orderstatus' => 2,
            'orderid' => $post['orderid'],
            'userid' => $this->userid,
            'table' => $this->table,
            'desc' => "选择绑定教练，教练id：{$post['coachid']}",
        ];

        $awhere = ['id' => $apply['id']];
        $aupdate = [
            'where' => $awhere,
            'data' => [
                'status' => 2,
            ],
        ];

        \think\facade\Db::startTrans();
        try {
            $ans = $this->updateTable('order', $update); //订单
            $row = $this->updateTable('apply_order', $aupdate); //订单
            $log = $this->orderLog($log); ////记录
            // 提交事务
            if ($ans && $log && $row) {
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $post['coachid'],
                    'reciveutable' => 'coach',
                    'msgtitle' => '您已被学员选择为学车教练',
                    'msgtext' => "{$time}，您已被学员选择为学车教练，学员：{$this->user['membertruename']}"
                ];
                $this->addnotice($notice);
                \think\facade\Db::commit();
                return $this->json($ans, 1001, '绑定成功');
            } else {
                \think\facade\Db::rollback();
                return $this->json($ans, 2000, '绑定失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return $this->json($ans, 2000, '确认失败');
        }
    }

    /**
     * 开始练车
     */
    public function confirmPractice()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 3],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可练车订单');
        }

        if ($info['memberid'] != $this->userid) {
            return $this->json([], 2000, '无权限确认');
        }

        $where = ['orderid' => $post['orderid']];
        $update = [
            'where' => $where,
            'data' => [
                'status' => 4,
            ],
        ];

        $log = [
            'orderstatus' => 4,
            'orderid' => $post['orderid'],
            'userid' => $this->userid,
            'table' => $this->table,
            'desc' => "确认练车",
        ];

        \think\facade\Db::startTrans();
        try {
            $ans = $this->updateTable('order', $update); //订单
            $row = $this->setOrderTime($info);
            $log = $this->orderLog($log); ////记录
            // 提交事务
            if ($ans && $row && $log) {
                \think\facade\Db::commit();
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $info['coachid'],
                    'reciveutable' => 'coach',
                    'msgtitle' => '订单开始练车',
                    'msgtext' => "{$time}，学员：{$this->user['membertruename']} 已确认开始练车"
                ];
                $this->addnotice($notice);
                return $this->json($ans, 1001, '确认成功');
            } else {
                \think\facade\Db::rollback();
                return $this->json($ans, 2000, '确认失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return $this->json($ans, 2000, $e->getMessage());
        }
    }

    /**
     * 延期订单
     */
    public function delayOrder()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 4],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可延期订单');
        }

        if ($info['memberid'] != $this->userid) {
            return $this->json([], 2000, '无权限延期');
        }

        $info = $this->findTable('order', ['where' => [
            ['orderid', '=', $post['orderid']],
        ]]);

        //更新订单
        $where = ['orderid' => $post['orderid']];
        $update = [
            'where' => $where,
            'data' => [
                'status' => 5,
            ],
        ];

        //订单记录写入
        $log = [
            'orderstatus' => 5,
            'orderid' => $post['orderid'],
            'userid' => $this->userid,
            'table' => $this->table,
            'desc' => "发起延期",
        ];

        \think\facade\Db::startTrans();
        try {
            $ans = $this->updateTable('order', $update); //订单
            $row = $this->setOrderTime($info, 1);
            $log = $this->orderLog($log); ////记录
            // 提交事务
            if ($ans && $row && $log) {
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $info['coachid'],
                    'reciveutable' => 'coach',
                    'msgtitle' => '订单已被延期',
                    'msgtext' => "{$time}，订单已被延期，学员：{$this->user['membertruename']} 已发起延期"
                ];
                $this->addnotice($notice);
                \think\facade\Db::commit();
                return $this->json($ans, 1001, '延期成功');
            } else {
                \think\facade\Db::rollback();
                return $this->json($ans, 2000, '延期失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return $this->json($ans, 2000, '延期失败');
        }
    }

    /**
     * 已完成订单
     */
    public function completeOrder()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', 'in', [4, 5]],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可确认订单');
        }

        if ($info['memberid'] != $this->userid) {
            return $this->json([], 2000, '无权限可确认');
        }

        $where = [];
        $where[] = ['orderid', '=', $post['orderid']];
        $where[] = ['status', 'in', [1, 3]];
        $order_timing = $this->findTable('order_timing', ['where' => $where]);

        $order_timing['coachid'] = $info['coachid'];
        $order_timing['memberid'] = $info['memberid'];
        $order_timing['amount'] = $info['amount'];

        $ans = $this->resultsEndTo($order_timing, 1);
        if ($ans) {
            $time = date('Y-m-d H:i:s');
            $notice = [
                'type' => 2,
                'userid' => 0,
                'reciveutype' => 2,
                'reciveuid' => $info['coachid'],
                'reciveutable' => 'coach',
                'msgtitle' => '订单已完成',
                'msgtext' => "{$time}，订单已确认完成，学员：{$this->user['membertruename']} 已确认"
            ];
            $this->addnotice($notice);
            return $this->json($ans, 1001, '订单确认完成');
        } else {
            return $this->json($ans, 2000, '操作失败');
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $get = input('get.');

        $where = $data = [];
        if (isset($get['status']) && in_array($get['status'], [1, 2, 3, 4, 5, 6, 7, 0])) {
            $where[] = ['status', '=', $get['status']];
        }

        $where[] = ['isdel', '=', 0];
        $where[] = ['memberid', '=', $this->userid];
        $data['where'] = $where;
        $tableName = 'order';
        $data['totalCount'] = $this->countTable($tableName, $data);
        $data = $this->buildCount($data);
        $data['order'] = 'updatetime desc';
        $list = $this->listTable($tableName, $data);

        $coach = $this->listTable('coach', [
            'where' => [
                'coachid' => array_column($list, 'coachid'),
            ],
            'field' => 'coachavatar,coachtruename,coachbirthday,coachid,coachsex,coachage',
        ]);

        $apply_order = $this->listTable('apply_order', [
            'where' => [
                ['coach.status', '=', 3],
                ['apply_order.orderid', 'in', array_column($list, 'orderid')],
            ],
            'join' => [
                ['coach coach', 'coach.coachid = apply_order.coachid', 'inner'],
            ],
            'field' => 'apply_order.orderid, count(apply_order.id) as count',
            'group' => 'apply_order.orderid',
        ]);

        $order_timing = $this->listTable('order_timing', [
            'where' => [
                ['orderid', 'in', array_column($list, 'orderid')],
            ],
            'field' => 'endtime, orderid',
            'group' => 'orderid',
        ]);

        foreach ($list as $key => $val) {
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);
            $list[$key]['updatetime'] = empty($val['updatetime']) ? '' : date('Y-m-d H:i:s', $val['updatetime']);
            $list[$key]['imgs'] = empty($val['imgs']) ? [] : explode(',', $val['imgs']);
            foreach ($coach as $cv) {
                if ($cv['coachid'] == $val['coachid']) {
                    $list[$key]['coachtruename'] = $cv['coachtruename'];
                    $list[$key]['coachavatar'] = $cv['coachavatar'];
                    $list[$key]['coachex'] = $cv['coachsex'];
                    $list[$key]['coachage'] = empty($cv['coachbirthday']) ? (empty($cv['coachage']) ? '暂无' : $cv['coachage']) : birthday($cv['coachbirthday']);
                }
            }
            $list[$key]['applycount'] = 0;
            foreach ($apply_order as $v) {
                if ($v['orderid'] == $val['orderid']) {
                    $list[$key]['applycount'] = $v['count'];
                }
            }

            foreach ($order_timing as $tv) {
                if ($tv['orderid'] == $val['orderid'] && $val['status'] == 5) {
                    $list[$key]['countdown'] = timer($tv['endtime']);
                }
            }
        }

        $data['data'] = $list;
        return $this->json($data);
    }
    
    /**
     *
     */
    public function getAwaitOrder()
    {
        $get = input('get.');

        $where = ['order.memberid' => $this->userid];
        $info = $this->findTable('order', [
            'where' => $where,
            'join' => [
                ['coach coach', 'coach.coachid = order.coachid'],
            ],
            'field' => 'order.*,coach.coachavatar,coach.coachtruename,coach.coachbirthday,coach.coachid,coach.coachsex,coach.coachid',
            'order' => 'orderid desc',
        ]);

        return $this->json($info, 1000);
    }
}
